import java.util.Arrays;

public class LCS {
    private static final int N = 20;
    private static int[][] c = new int[N][N];

    public static int lcsLength(String a, String b) {
        int m = a.length();
        int n = b.length();
        for(int i = 0; i <= m; i++) {
            c[i][0] = 0;
        }
        for(int i = 0; i <= n; i++) {
            c[0][i] = 0;
        }
        for(int i = 1; i <= m; i++) {
            for(int j = 1; j <= n; j++) {
                if(a.charAt(i - 1) == b.charAt(j - 1)) {
                    c[i][j] = c[i - 1][j - 1] + 1;
                } else {
                    c[i][j] = Math.max(c[i - 1][j], c[i][j - 1]);
                }
            }
        }
        return c[m][n];
    }

    public static String buildlcs(String a, String b) {
        int k;
        int i = a.length();
        int j = b.length();
        k = lcsLength(a, b);
        char[] s = new char[k];
        while(k > 0) {
            if(c[i][j] == c[i - 1][j]) {
                i--;
            } else if(c[i][j] == c[i][j - 1]) {
                j--;
            } else {
                s[--k] = a.charAt(i - 1);
                i--;
                j--;
            }
        }
        return Arrays.toString(s).replaceAll("[, \\[\\]]", "");
    }

    public static void main(String[] args) {
        String a = "abcbdb";
        String b = "acbbabdbb";
        System.out.println("最长公共子序列长度 : " + lcsLength(a, b));
        System.out.println("最长公共子序列： " + buildlcs(a, b));
    }
}